package com.example.shop_front_api.service.impl;

import com.example.shop_front_api.entity.MemberAddress;
import com.example.shop_front_api.mapper.MemberAddressMapper;
import com.example.shop_front_api.service.MemberAddressService;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MemberAddressServiceImpl implements MemberAddressService {
    @Autowired
    private MemberAddressMapper memberAddressMapper;

    @Override
    @Transactional
    public int addAddress(MemberAddress address){
        if(address .getIsDefault() == 1){
            memberAddressMapper.clearDefaultAddress(address.getMemberId());
        }
        return memberAddressMapper.insertAddress(address);
    }

    @Override
    public List<MemberAddress> getAddressByMemberId(int memberId) {
        return memberAddressMapper.getAddressListByMemberId(memberId);
    }

    @Override
    public MemberAddress getAddressById(int id) {
        return memberAddressMapper.getAddressById(id);
    }

    @Override
    @Transactional
    public int updateAddress(MemberAddress address) {
        if(address.getIsDefault() == 1){
            memberAddressMapper.clearDefaultAddress(address.getMemberId());
        }
        return memberAddressMapper.updateAddress(address);
    }

    @Override
    @Transactional
    public int deleteAddress(int id, int memberId) {
        MemberAddress address = memberAddressMapper.getAddressById(id);
        if (address != null && address.getIsDefault() == 1) {
            throw new RuntimeException("默认地址不能删除");
        }
        return memberAddressMapper.deleteAddress(id, memberId);
    }

    @Override
    @Transactional
    public int setDefaultAddress(int id, int memberId) {
        memberAddressMapper.clearDefaultAddress(memberId);
        return memberAddressMapper.setDefaultAddress(id, memberId);
    }

    @Override
    public MemberAddress getDefaultAddressByMemberId(int memberId) {
        return memberAddressMapper.getDefaultAddressByMemberId(memberId);
    }
}
